package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.config.minio.properties.MinioProperties;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    MinioProperties minioProperties;

    @Autowired
    MinioClient minioClient;

    @Override
    public String uploadToMinio(MultipartFile file) throws Exception {
        //3、上传文件
        //3.1-加上唯一前缀UUID保证文件名不重复【优化一】
        //3.2-当天时间作为目录
        String date = DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        String originalFilename = date + "/" + UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        PutObjectOptions putObjectOptions = new PutObjectOptions(file.getSize(), -1);
        putObjectOptions.setContentType(file.getContentType());
        // 上传
        minioClient.putObject(minioProperties.getBucketName(), originalFilename, inputStream, putObjectOptions);
        //4、返回文件的访问地址
//        if(!this.minioClient.bucketExists(minioProperties.getBucket())){
//            this.minioClient.makeBucket(minioProperties.getBucket());
//        }
        String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + originalFilename;
        return url;
    }
}
